package cn.ybz21.hibot.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

public class NetCenter {

	public String httpGet(String path) throws IOException {
		URL url = new URL(path);
		StringBuilder strBuilder = new StringBuilder();
		BufferedReader bufferedReader = new BufferedReader(
				new InputStreamReader(url.openStream()));
		for (String s = bufferedReader.readLine(); s != null; s = bufferedReader
				.readLine()) {
			strBuilder.append(s);
		}
		// System.out.println(strBuilder);

		return strBuilder.toString();
	}

	public String httpPost(String url, List<NameValuePair> params) {
		String jsonData = "";
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost httpRequest = new HttpPost(url);
			httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				InputStream is = httpResponse.getEntity().getContent();
				BufferedReader br = new BufferedReader(
						new InputStreamReader(is));
				String line = "";
				while ((line = br.readLine()) != null) {
					jsonData += line + "\r\n";
				}
			}
		} catch (IOException e) {
			System.out.println("network error!");
		}
		return jsonData;
	}
}
